package pl.edu.mimuw.irs.rcp.persistence.role;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import pl.edu.mimuw.irs.core.model.design.resource.Role;
import pl.edu.mimuw.irs.core.model.design.resource.Roles;
import pl.edu.mimuw.irs.rcp.persistence.AbstractPersistence;

public class RolesPersistence extends AbstractPersistence<Roles> {

	// *** Attributes
	
	// *** Methods

	@Override
	public Roles loadFromStream(InputStream stream) throws Exception {
		Roles roles = new Roles();
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		
		for (String line = reader.readLine(); line != null; line = reader.readLine()) {
			String role = line.trim();
			if (role.equals("")) continue;
			if (roles.containsKey(role)) continue;
			roles.add(new Role(role));
		}
		return roles;
	}

	@Override
	public void writeToStream(Roles object, OutputStream stream)
			throws Exception {
		
		Roles roles = (Roles)object;
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
		
		for (Role role : roles.values()) {
			writer.write(role.getName()); 
			writer.newLine();
		}
		writer.close();
	}


}
